<?php

namespace stlswm\WxSubscriptionPHP\Web;

use stlswm\WxSubscriptionPHP\CurlHttp;
use stlswm\WxSubscriptionPHP\Response;

/**
 * Class OAuth2
 *
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
 *
 * @package stlswm\WxSubscriptionPHP\Web
 * @mixin CurlHttp
 */
class OAuth2
{
    use CurlHttp;

    /**
     * 获取微信授权连接
     * 第一步：用户同意授权，获取code
     *
     * @param string $appId
     * @param string $redirectUri
     * @param string $scope
     * @param string $state
     *
     * @return string
     * @Author: wm
     * @Date  : 19-2-23
     * @Time  : 上午10:35
     */
    public static function authorizeUrl(
        string $appId,
        string $redirectUri,
        string $scope = 'snsapi_base',
        string $state = ''
    ): string {
        $redirectUri = urlencode($redirectUri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }

    /**
     * 第二步：通过code换取网页授权access_token
     *
     * @param string $appId
     * @param string $secret
     * @param string $code
     *
     * @return Response
     * @Author: wm
     * @Date  : 19-2-23
     * @Time  : 上午10:38
     */
    public static function getAccessToken(string $appId, string $secret, string $code): Response
    {
        $api = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$secret}&code={$code}&grant_type=authorization_code";
        return self::get($api);
    }

    /**
     * 第三步：刷新access_token（如果需要）
     *
     * @param string $appId
     * @param string $refreshToken
     *
     * @return Response
     * @Author: wm
     * @Date  : 19-2-23
     * @Time  : 上午10:43
     */
    public static function refreshAccessToken(string $appId, string $refreshToken): Response
    {
        $api = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appId}&grant_type=refresh_token&refresh_token={$refreshToken}";
        return self::get($api);
    }

    /**
     * 第四步：拉取用户信息(需scope为 snsapi_userinfo)
     *
     * @param string $accessToken
     * @param string $openId
     * @param string $lang
     *
     * @return Response
     * @Author: wm
     * @Date  : 19-2-23
     * @Time  : 上午10:45
     */
    public static function userInfo(string $accessToken, string $openId, string $lang = 'zh_CN '): Response
    {
        $api = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang={$lang}";
        return self::get($api);
    }

    /**
     * 检验授权凭证（access_token）是否有效
     *
     * @param string $accessToken
     * @param string $openId
     *
     * @return Response
     * @Author: wm
     * @Date  : 19-2-23
     * @Time  : 上午10:46
     */
    public static function checkAccessToken(string $accessToken, string $openId): Response
    {
        $api = "https://api.weixin.qq.com/sns/auth?access_token={$accessToken}&openid={$openId}";
        return self::get($api);
    }
}